
package services

import (
	"beego_blog/models"
	"net/url"
	"strconv"
	"log"
	"time"
)

type TeacherService struct {
	baseService
}

func (c *TeacherService) Add(params url.Values) bool {
	teacher := models.Teacher{}
	cols := []string{}

	if params.Has("name") {
		cols = append(cols, "name")
		teacher.Name = params.Get("name")
	}
	if params.Has("phone") {
		cols = append(cols, "phone")
		teacher.Phone = params.Get("phone")
	}
	if params.Has("retrie_time") {
		cols = append(cols, "retrie_time")
		teacher.Retrie_time, _ = time.Parse("2006-01-02 15:04:05", params.Get("retrie_time"))
	}

	if _, err := c.o.Insert(&teacher); err != nil {
		log.Println("Add err", err)
		return false
	} else {
		return true
	}
}

func (c *TeacherService) Delete(params url.Values) bool {
	teacher := models.Teacher{}
	teacher.Id, _ = strconv.Atoi(params.Get("id"))

	if _, err := c.o.Delete(&teacher); err != nil {
		log.Println("Delete err", err)
		return false
	} else {
		return true
	}
}

func (c *TeacherService) Query(params url.Values) []*models.Teacher {
	teachers := []*models.Teacher{}
	teacher := models.Teacher{}
	cols := []string{}

	if params.Has("name") {
		cols = append(cols, "name")
		teacher.Name = params.Get("name")
	}
	if params.Has("phone") {
		cols = append(cols, "phone")
		teacher.Phone = params.Get("phone")
	}
	if params.Has("retrie_time") {
		cols = append(cols, "retrie_time")
		teacher.Retrie_time, _ = time.Parse("2006-01-02 15:04:05", params.Get("retrie_time"))
	}

	Query_by_model(c.o, "id", cols, teacher, &teachers)
	return teachers
}

func (c *TeacherService) QueryByPk(params url.Values) models.Teacher {
	teacher := models.Teacher{}
	teacher.Id, _ = strconv.Atoi(params.Get("id"))

	c.o.Read(&teacher)
	return teacher
}

func (c *TeacherService) Update(params url.Values) bool {
	teacher := models.Teacher{}
	cols := []string{}
	teacher.Id, _ = strconv.Atoi(params.Get("id"))

	if params.Has("name") {
		cols = append(cols, "name")
		teacher.Name = params.Get("name")
	}
	if params.Has("phone") {
		cols = append(cols, "phone")
		teacher.Phone = params.Get("phone")
	}
	if params.Has("retrie_time") {
		cols = append(cols, "retrie_time")
		teacher.Retrie_time, _ = time.Parse("2006-01-02 15:04:05", params.Get("retrie_time"))
	}

	if _, err := c.o.Update(&teacher, cols...); err != nil {
		log.Println("Update err", err)
		return false
	} else {
		return true
	}
}
	
